﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class ReflectionPropertyGetter : IPropertyGetter
    {
        private readonly static ConditionalWeakTable<object, NamedArgument[]> propertyGetterCache = new ConditionalWeakTable<object, NamedArgument[]>();
        private readonly object _instance;
        public ReflectionPropertyGetter(object instance)
        {
            this._instance = instance;
        }
        public NamedArgument[] GetNamedArguments()
        {
            NamedArgument[] namedArguments;
            if (propertyGetterCache.TryGetValue(_instance, out namedArguments))
            {
                return namedArguments;
            }
            var properties = _instance.GetType().GetProperties();
            namedArguments = new NamedArgument[properties.Length];
            for (int i = 0; i < namedArguments.Length; i++)
            {
                var propertyInfo = properties[i];
                var getter = propertyInfo.GetValue(_instance, null);
                namedArguments[i] = new NamedArgument(propertyInfo.PropertyType, propertyInfo.Name, getter);
            }
            propertyGetterCache.Add(_instance, namedArguments);
            return namedArguments;
        }
    }
}
